package ui;

import java.awt.event.*;

public class Input extends KeyAdapter {

  public static int CMD_N = 0;
  public static int CMD_NE = 1;
  public static int CMD_E = 2;
  public static int CMD_SE = 3;
  public static int CMD_S = 4;
  public static int CMD_SW = 5;
  public static int CMD_W = 6;
  public static int CMD_NW = 7;

  boolean waiting;
  int command;

  public Input() {
    command = -1;
    waiting = false;
  }

  public synchronized void keyPressed(KeyEvent e) {

    if(!waiting) return;

    /* arrow movement keys */
    if(e.getKeyCode() == KeyEvent.VK_UP) command = CMD_N;
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT) command = CMD_E;
    else if(e.getKeyCode() == KeyEvent.VK_DOWN) command = CMD_S;
    else if(e.getKeyCode() == KeyEvent.VK_LEFT) command = CMD_W;

    /* vi movement keys (yuhjklbn) */
    else if(e.getKeyChar() == 'k') command = CMD_N;
    else if(e.getKeyChar() == 'u') command = CMD_NE;
    else if(e.getKeyChar() == 'l') command = CMD_E;
    else if(e.getKeyChar() == 'n') command = CMD_SE;
    else if(e.getKeyChar() == 'j') command = CMD_S;
    else if(e.getKeyChar() == 'b') command = CMD_SW;
    else if(e.getKeyChar() == 'h') command = CMD_W;
    else if(e.getKeyChar() == 'y') command = CMD_NW;

    /* numeric (keypad) movement keys */
    else if(e.getKeyChar() == '8') command = CMD_N;
    else if(e.getKeyChar() == '9') command = CMD_NE;
    else if(e.getKeyChar() == '6') command = CMD_E;
    else if(e.getKeyChar() == '3') command = CMD_SE;
    else if(e.getKeyChar() == '2') command = CMD_S;
    else if(e.getKeyChar() == '1') command = CMD_SW;
    else if(e.getKeyChar() == '4') command = CMD_W;
    else if(e.getKeyChar() == '7') command = CMD_NW;

    notify();

  }

  public synchronized int getInput() {

    waiting = true;
    while(command == -1) {
      try { wait(); }
      catch(InterruptedException e) { }
    }
    waiting = false;
    int c = command;
    command = -1;
    return(c);

  }

}
